﻿using DBModels;
using Method.Token;
using Models.operResult;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Api.WDS.Methods
{
    public class LogInMet
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        public OperResult<string> UserLogIn(string uid, string pwd, string sessionId)
        {
            using (ArticeContext context = new ArticeContext())
            {
                var info = context.Accounts.FirstOrDefault(u => u.Id == Convert.ToInt32(uid));
                if (info is null)
                    return OperResult<string>.Failed("该用户不存在");
                if (info.Password == pwd)
                {
                    //创建令牌
                    var token = JwtOperating.CreateJwt(sessionId, uid);
                    //持久化
                    if (new RedisHelper.LogIn.UserLogIn().InsertToken(token, sessionId))
                    {
                        //登录成功,返回令牌
                        return OperResult<string>.Succeed(token);
                    }
                    else
                        return OperResult<string>.Failed("网络错误,请稍后重试");
                }
                else
                    return OperResult<string>.Failed("账户密码不正确");
            }
        }
    }
}
